<template>
  <div class="login-view">
    <div class="login-box">
      <div class="icon-info">
        <h2 class="txt">统一认证平台</h2>
        <img class="login-bg" :src="loginBg" style="width: 400px;height: 400px;"/>
      </div>

      <div class="login-form">
        <img :src="logoImg" style="width: 70px;height: 70px"/>
        <h2 style="margin-bottom: 20px">登录统一认证平台</h2>

        <el-form :roles="rules" ref="formRef" :model="formData">
          <el-form-item prop="uname">
            <el-input style="width: 340px" type="text" placeholder="请输入用户名" v-model="formData.uname">
              <template #prepend><span class="label">用户名：</span></template>
            </el-input>
          </el-form-item>
          <el-form-item prop="passwd">
            <el-input style="width: 340px" type="password" placeholder="请输入用户密码" v-model="formData.passwd">
              <template #prepend><span class="label">密码：</span></template>
            </el-input>
          </el-form-item>
          <el-form-item prop="code">
            <el-input style="width: 340px" type="password" placeholder="请输入验证码" v-model="formData.code">
              <template #prepend><span class="label">验证码：</span></template>
              <template #append><img :src="codeImage" alt="验证码" style="width: 64px;height: 32px" @click="onGetCapcha"/></template>
            </el-input>
          </el-form-item>
        </el-form>
        <div style="width: 340px;display: flex;justify-content: flex-end">
          <el-checkbox v-model="rememberPwd">记住密码</el-checkbox>
        </div>
        <el-button
            style="width: 340px;margin-top: 10px;margin-bottom: 50px"
            :disabled="!formData.uname || !formData.passwd || !flag"
            type="primary"
            @click="onLogin(formRef)"
        >登录
        </el-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, onUnmounted} from "vue";
import loginBg from '@/assets/img_bg.png';
import logoImg from '@/assets/logo.png';
import {ref} from "vue";
import {getCaptcha, login, LoginArgs} from "@/service/UserManager";
import {setAdminToken, setIsAdmin} from '@/utils/setToken';
import router from "@/router";
import {LoginDto} from "@/service/entity/LoginDto";
import {ElMessage, FormInstance, ElLoading} from "element-plus";

const rememberPwd = ref(false)
const codeImage = ref('')

const changeRememberPwd = () => {
  rememberPwd.value = !rememberPwd.value
}

const formData = reactive<LoginArgs>({
  uname: '',
  passwd: '',
  uuid: '',
  code: ''
})
const formRef = ref<FormInstance>()
const rules = reactive({
  uname: [
    {required: true, message: '用户名不可为空', trigger: 'blur'},
  ],
  passwd: [{
    required: true, message: '用户密码不可为空', trigger: 'blur'
  }],
  code: [{
    required: true, message: '验证码不可为空', trigger: 'blur'
  }]
})

let flag = ref(true)

const doLogin = (e) => {
  if (e.keyCode !== 13 || !flag.value) {
    return
  }
  flag.value = false
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  onLogin(formRef.value).then(() => {
    setTimeout(() => {
      flag.value = true
      loading.close()
    }, 1000)
  });
}

const onGetCapcha = async () => {
  const captcha = await getCaptcha()
  codeImage.value = captcha.codeImageBase64
  formData.uuid = captcha.uuid
}

onMounted(() => {
  rememberPwd.value = localStorage.getItem('rememberPwd') === '1'
  if (rememberPwd.value) {
    formData.uname = localStorage.getItem('loginUsername') || ''
    formData.passwd = localStorage.getItem('loginPassword') || ''
  }
  window.addEventListener('keydown', doLogin)
  onGetCapcha()
})

onUnmounted(() => {
  window.removeEventListener('keydown', doLogin, false)
})


const onLogin = async (formRef: FormInstance | undefined) => {
  if (!formRef) {
    return
  }
  await formRef.validate(async (valid, fields) => {
    if (valid) {
      try {
        const res = await login(formData)
        if (!res) return
        if (rememberPwd.value) {
          localStorage.setItem('rememberPwd', '1')
          localStorage.setItem('loginUsername', formData.uname)
          localStorage.setItem('loginPassword', formData.passwd)
        } else {
          localStorage.setItem('rememberPwd', '0')
          localStorage.removeItem('loginUsername')
          localStorage.removeItem('loginPassword')
        }
        formRef.resetFields()
        setUserData(res)
        router.push('/myAppList')
      } finally {
        onGetCapcha()
      }
    } else {
      ElMessage.error('用户名密码跟验证码不可为空')
    }
  })
}

function setUserData(userData: LoginDto) {
  setAdminToken(userData.token)
  setIsAdmin(userData.isAdmin)
  localStorage.setItem('uid', userData.uid)
  localStorage.setItem('name', userData.name)
  localStorage.setItem('uname', userData.uname)
  localStorage.setItem('isAdmin', userData.isAdmin ? '1' : '0')
  localStorage.setItem('AppUserData', JSON.stringify(userData))
}

</script>

<style lang="scss">
.login-view {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #0d1d30;

  .login-box {
    width: 1100px;
    height: 550px;
    box-sizing: border-box;
    border-radius: 10px;
    overflow: hidden;
    background: #19293b;
    display: flex;
    align-items: center;
    justify-content: center;

    .icon-info {
      height: 100%;
      display: flex;
      flex: 1;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      .txt {
        color: white;
      }

      .login-bg {
        width: 40%;
        height: 55%;
      }
    }

    .login-form {
      width: 420px;
      height: 100%;
      background: white;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      .label {
        display: flex;
        justify-content: flex-end;
        width: 50px;
      }
    }

    .ap-input-group__append {
      box-shadow: none;
      background-color: white;
      border: var(--ap-border);
      border-left: none;
    }
  }
}
</style>